package com.clss.emergencycall.utils

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.webkit.MimeTypeMap
import com.clss.emergencycall.utils.PublicUtils
import com.clss.emergencycall.utils.VersionUpdataHelper
import java.io.File


/**
 * @author sonia
 * @date 2019/1/30
 */
class InstallAppUtils {
    companion object {
        val TAG= "InstallAppUtils"
        //启动安装
        fun openFile(mContext: Context, path: String): Intent{
            val downloadFileUri = PublicUtils.getUri(mContext, path)
            var intent = Intent()
            when {
                Build.VERSION.SDK_INT < Build.VERSION_CODES.M -> {
                    intent.setDataAndType(downloadFileUri, "application/vnd.android.package-archive")
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) //避免重复打开
                    mContext.startActivity(intent)
                }
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
                    intent = Intent(Intent.ACTION_VIEW)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    intent.setDataAndType(downloadFileUri, "application/vnd.android.package-archive")
                    mContext.startActivity(intent)
                }
                else -> {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    intent.action = Intent.ACTION_VIEW
                    val mimeType = getMIMEType(File(path))
                    intent.setDataAndType(downloadFileUri, mimeType)
                    try {
                        mContext.startActivity(intent)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
            return intent
        }

        private fun getMIMEType(file: File): String? {
            val name = file.name
            val fileName = name.substring(name.lastIndexOf(".") + 1, name.length).toLowerCase()
            return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileName)
        }

        /**
         * 检查版本更新
         * 除了下载中状态都要检查
         */
//        fun updateTinkerVersion(context: Context): Boolean {
//            //初始化差量包版本
//            if (BuildConfig.MESSAGE.equals(BuildConfig.BASE_MESSAGE)) {
//                SpHelper.getInstance().patchVersion = 0
//            } else {
//                val tinker = Tinker.with(context)
//                val patchVersion = tinker.tinkerLoadResultIfPresent.getPackageConfigByName("patchVersion")
//                if (patchVersion != null) {
//                    SpHelper.getInstance().patchVersion = Integer.parseInt(patchVersion)
//                }
//            }
//            if (Constant.appDownloadState != 0) {
//                return true
//            }
//            return false
//        }

        //位置权限设置页面
        fun toLocationSettings(context: Context) {
            val intent = Intent()
            intent.action = Settings.ACTION_LOCATION_SOURCE_SETTINGS
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            try {
                context.startActivity(intent)
            } catch (ex: ActivityNotFoundException) {
                //如果页面无法打开，进入设置页面
                intent.action = Settings.ACTION_SETTINGS
                try {
                    context.startActivity(intent)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }

        var noticeDialog: VersionUpdataHelper.CustomDialog? = null
        fun showNoticeDialog(context: Context, view: CheckVersionView, vararg isReurnOkResult: Boolean) {
            val builder = VersionUpdataHelper.CustomDialog.Builder(context)
            builder.setMessage("检测到您没有允许通知权限，是否允许？")
            builder.setPositiveButton("是") { dialog, _ ->
                dialog.dismiss()
                val localIntent = Intent()
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                localIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                localIntent.data = Uri.fromParts("package", context.packageName, null)
                context.startActivity(localIntent)
                if (isReurnOkResult.isNotEmpty() && isReurnOkResult[0]) {
                    view.checkVersion()
                }
            }
            builder.setNegativeButton("否") { dialog, _ ->
                dialog.dismiss()
                view.checkVersion()
            }
            noticeDialog?.let { it.dismiss() }
            noticeDialog = builder.create()
            noticeDialog?.setCancelable(false)
            noticeDialog?.show()
        }
//
//        fun initShortcutInfo(context: Context?){
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
//                val shortcutInfoList: MutableList<ShortcutInfo> = mutableListOf()
//                val shortcutManager = context?.getSystemService(ShortcutManager::class.java)
//                val videoId = "video"
//                val silenceId = "silence"
//                val sosId = "SOS"
//                //没有这个id也不会抛异常
//                val disabledShortcutIds = mutableListOf(sosId, silenceId, videoId)
//                if (null == AppDatabaseHelper.getInstance().getHostService()) {
//                    shortcutManager?.disableShortcuts(disabledShortcutIds, "此功能暂不可用")
//                    shortcutManager?.dynamicShortcuts = shortcutInfoList
//                } else {
//                    var alarmModel: ModelDetail? = null
//                    var silenceAlarmModel: ModelDetail? = null
//                    val list = AppDatabaseHelper.getInstance().getMenuGroupsByAreaCode(CommonUtils.getCode())
//                    for (allModelBean in list) {
//                        allModelBean.services = Gson().fromJson(allModelBean.item, object : TypeToken<List<ModelDetail?>?>() {}.type)
//                        for (modelDetail in allModelBean.services) {
//                            if (modelDetail.id == Constant.FUNCTION_SWITCH_ALARM) {
//                                alarmModel = modelDetail
//                                if(alarmModel != null && silenceAlarmModel!=null){
//                                    break
//                                }
//                            } else if (modelDetail.id == Constant.FUNCTION_SWITCH_ALARM_SILENCE) {
//                                silenceAlarmModel = modelDetail
//                                if(alarmModel != null && silenceAlarmModel!=null){
//                                    break
//                                }
//                            }
//                        }
//                        if(alarmModel != null && silenceAlarmModel!=null){
//                            break
//                        }
//                    }
//                    val videoIntent = Intent(context, HomeActivity::class.java).setAction("com.safe.peoplesafety.shortcut.alarm").putExtra("alarmType", Constant.FUNCTION_SWITCH_ALARM)
//                    val silenceIntent = Intent(context, HomeActivity::class.java).setAction("com.safe.peoplesafety.shortcut.alarm").putExtra("alarmType", Constant.FUNCTION_SWITCH_ALARM_SILENCE)
//
//
//                    alarmModel?.let {
//                        val videoShortcut = ShortcutInfo.Builder(context, videoId)
//                                .setShortLabel(alarmModel?.name)
//                                .setIcon(Icon.createWithResource(context, R.mipmap.video_alarm_shortcut))
//                                .setIntent(videoIntent)
//                                .build()
//                        shortcutInfoList.add(videoShortcut)
//                    }
//                    silenceAlarmModel?.let {
//                        val silenceShortcut = ShortcutInfo.Builder(context, silenceId)
//                                .setShortLabel(silenceAlarmModel?.name)
//                                .setIcon(Icon.createWithResource(context, R.mipmap.silence_alarm_shortcut))
//                                .setIntent(silenceIntent)
//                                .build()
//                        shortcutInfoList.add(silenceShortcut)
//                    }
//                }
//                val sosIntent = Intent(context, SosActivity::class.java).setAction("com.safe.peoplesafety.shortcut.alarm")
//                //演示模式有sos，切换sos不修改本地存储的sos数据
//                if (SpHelper.getInstance().hasSos() || SpHelper.getInstance().workingMode > 0) {
//                    val sosShortcut = ShortcutInfo.Builder(context, sosId)
//                            .setShortLabel("SOS报警静默黑屏")
////                        .setLongLabel("SOS报警静默黑屏")
//                            .setIcon(Icon.createWithResource(context, R.mipmap.sos_alarm_shortcut))
//                            .setIntent(sosIntent)
//                            .build()
//                    shortcutInfoList.add(sosShortcut)
//                }
//                shortcutManager?.dynamicShortcuts = shortcutInfoList
//
//                val enableShortcutIds = mutableListOf<String>()
//                for (info in shortcutInfoList) {
//                    when (info.id) {
//                        sosId -> {
//                            enableShortcutIds.add(sosId)
//                            disabledShortcutIds.remove(sosId)
//                        }
//                        videoId -> {
//                            enableShortcutIds.add(videoId)
//                            disabledShortcutIds.remove(videoId)
//                        }
//                        silenceId -> {
//                            enableShortcutIds.add(silenceId)
//                            disabledShortcutIds.remove(silenceId)
//                        }
//                    }
//                }
//                Lg.i(TAG, "---disableShortcuts==$disabledShortcutIds")
//                Lg.i(TAG, "---enableShortcuts==$enableShortcutIds")
//                shortcutManager?.disableShortcuts(disabledShortcutIds, "此功能暂不可用")
//                shortcutManager?.enableShortcuts(enableShortcutIds)
//            }
//        }
    }


    interface CheckVersionView {
        fun checkVersion()
    }

}